package com.kiragame.couplescreen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.kiragame.couplescreen.AddContactDialogFragment.AddContactDialogListener;
import com.kiragame.couplescreen.EditContactDialogFragment.EditContactDialogListener;
import com.kiragame.couplescreen.KiraMessage.MessageType;
import com.kiragame.couplescreen.MenuFragment.OnSelectMenuListener;
import com.kiragame.couplescreen.lib.TouchImageView;
import com.kiragame.couplescreen.quickblox.QuickBloxManager;
import com.kiragame.couplescreen.rateapp.RateAppManager;
import com.kiragame.couplescreen.service.AppService;
import com.kiragame.couplescreen.service.NetworkReceiver;
import com.kiragame.couplescreen.service.NetworkReceiver.OnNetworkListener;
import com.kiragame.couplescreen.service.ServiceAppBroadcastReceiver;
import com.kiragame.couplescreen.utils.KiraGameLog;

public class MainActivity extends SlidingFragmentActivity {
	private SlidingMenu menu;
	private MenuFragment menuFragment;
	private ActionBar mActionBar;

	private String currentContact;
	private boolean isDone = true;
	private NetworkReceiver networkReceiver;
	private boolean isShowingProgessbar = false;

	// Main Layout
	private TouchImageView tvImage;
	private ProgressBar pbLoading;
	private ProgressDialog spinner;
	private TextView tvNotice;

	// Actionbar
	private ImageButton ibMenu;
	private TextView tvConnect;
	private TextView tvNumRefesh;
	private ImageButton ibDownload;
	private ImageButton ibReload;
	private Bitmap image;

	private long TIME_OUT = 60000;

	private final String FOLDER_NAME = "CoupleScreen";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Mint.initAndStartSession(this, "cc6d146e");
		// stop service
		stopService(new Intent(this, AppService.class));
		// KiraGameLog.d("service is running " +
		// isMyServiceRunning(AppService.class));

		generateDeviceContactID();
		settingActionbar();
		setContentView(R.layout.activity_main);
		findViewIDs();
		// QuickBloxManager.getInstance(this).clearQuickbloxManager();
		init();
		// setUpServer();

		settingSlidingMenu();
		// setUpServer();
		setEvent();
	}

	private void addRateAppDialog() {
		RateAppManager.getInstance(MainActivity.this).show();
	}

	private void init() {
		spinner = new ProgressDialog(this);
		spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		spinner.setCanceledOnTouchOutside(false);
		spinner.setCancelable(false);// avoid use click outside to

		// // dismiss dialog
		if (currentContact == null) {
			ibReload.setEnabled(false);
			showNotice("Please select contact to connect!");
		}
		// pbLoading.setVisibility(View.GONE);
		networkReceiver = new NetworkReceiver();
		networkReceiver.setOnNetworkListener(new OnNetworkListener() {

			@Override
			public void onOnline() {
				hideNotice();
			}

			@Override
			public void onOffine() {
				showNotice("Can't connect to server. Please check your network!");
			}
		});
		registerReceiver(networkReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));

		// MyKeypadListener myKeypadListener = new MyKeypadListener();
		// IntentFilter filterKP = new
		// IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
		// registerReceiver(myKeypadListener, filterKP);
		// Intent intent = new Intent(MainActivity.this,
		// MyKeypadListener.class);
		// sendBroadcast(intent);

		IntentFilter filter = new IntentFilter(
				QuickBloxManager.ACTION_CHANGE_UI_MAIN);
		LocalBroadcastManager.getInstance(this).registerReceiver(
				changeUIReceiver, filter);

		// setUpServer();
		loadAds();
	}

	private void loadAds() {
		AdView adView = (AdView) this.findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
	}

	private void findViewIDs() {
		tvImage = (TouchImageView) findViewById(R.id.tv_image);
		pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
		tvNotice = (TextView) findViewById(R.id.tv_notice);
	}

	public void showNotice(final String notice) {
		tvNotice.setText(notice);
		tvNotice.setVisibility(View.VISIBLE);
	}

	public void hideNotice() {
		tvNotice.setVisibility(View.GONE);
	}

	private void setUpServer() {
		QuickBloxManager.getInstance(this).setUpServer();
	}

	public void showProgessbar(String text) {
		isShowingProgessbar = true;
		spinner.setMessage(text);
		spinner.show();
		KiraGameLog.d("PB S " + isShowingProgessbar);
	}

	public void hideProgessbar() {
		if (spinner == null) {
			return;
		}
		spinner.dismiss();
		isShowingProgessbar = false;
		KiraGameLog.d("PB H " + isShowingProgessbar);
	}

	private void setEvent() {
		ibMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toggle();
				if (DataManager.getInstance(MainActivity.this).getUserID() != 0) {
					menuFragment.showUserID();
				}
			}
		});
		ibReload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String contact = DataManager.getInstance(MainActivity.this)
						.getCurrentContactID();
				sendRequest(menuFragment.contacts.get(contact));
				disableReload();
				ibDownload.setVisibility(View.GONE);
			}
		});

		ibDownload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				saveImageToFile(image);
			}
		});
	}

	protected void saveImageToFile(final Bitmap image) {
		if (image == null) {
			Toast.makeText(MainActivity.this, "Can not save this image!",
					Toast.LENGTH_LONG).show();
			return;
		}
		new SaveImageTask().execute();
	}

	protected void disableReload() {
		ibReload.setEnabled(false);
		new CountDownTimer(5000, 1000) {

			public void onTick(long millisUntilFinished) {
				int time = (int) (millisUntilFinished / 1000);
				tvNumRefesh.setText(Integer.toString(time) + "s");
			}

			public void onFinish() {
				ibReload.setEnabled(true);
				tvNumRefesh.setText("");
			}
		}.start();
	}

	private void settingActionbar() {
		mActionBar = getSupportActionBar();
		// mActionBar.hide();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayShowCustomEnabled(true);
		mActionBar.setDisplayShowTitleEnabled(false);
		// mActionBar.setCustomView(getActionbarView());
		View customView = getActionbarView();
		LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mActionBar.setCustomView(customView, layout);
	}

	private View getActionbarView() {
		View view = getLayoutInflater().inflate(R.layout.actionbar_main, null);
		ibMenu = (ImageButton) view.findViewById(R.id.ib_menu);
		tvConnect = (TextView) view.findViewById(R.id.tv_connect);
		tvNumRefesh = (TextView) view.findViewById(R.id.tv_num_refesh);
		ibDownload = (ImageButton) view.findViewById(R.id.ib_download);
		ibReload = (ImageButton) view.findViewById(R.id.ib_reload);
		return view;
	}

	private void generateDeviceContactID() {
		if (DataManager.getInstance(this).getDeviceContactID() == null) {
			String deviceId;

			final TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			if (mTelephony.getDeviceId() != null) {
				deviceId = mTelephony.getDeviceId(); // *** use for mobiles
			} else {
				deviceId = Settings.Secure.getString(getContentResolver(),
						Settings.Secure.ANDROID_ID); // *** use for tablets
			}
			DataManager.getInstance(this).setDeviceContactID(deviceId);
		}
		KiraGameLog.d("Device ID "
				+ DataManager.getInstance(this).getDeviceContactID());

	}

	private void settingSlidingMenu() {
		setBehindContentView(R.layout.menu_frame);
		FragmentTransaction t = this.getSupportFragmentManager()
				.beginTransaction();
		menuFragment = MenuFragment.newInstance();
		menuFragment.setOnSelectMenuListener(new OnSelectMenuListener() {

			@Override
			public void onSelectContact(String contact) {
				currentContact = contact;
				String contactName = menuFragment.contacts.get(contact);
				tvConnect.setText("Connecting to " + contact + "("
						+ contactName + ")");
				KiraGameLog.d("You choose " + contact + " with id "
						+ contactName + " to connect!");
				sendRequest(contactName);
				DataManager.getInstance(MainActivity.this).setCurrentContactID(
						contact);
				disableReload();
				ibDownload.setVisibility(View.GONE);
				toggle();
			}

			@Override
			public void onGetID() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onExit() {
				toggle();
				finish();
			}

			@Override
			public void onAddContact() {
				FragmentManager fm = getSupportFragmentManager();
				final AddContactDialogFragment addContactDialogFragment = new AddContactDialogFragment();
				addContactDialogFragment
						.setOnAddContactDialogListener(new AddContactDialogListener() {

							@Override
							public void onOKClickListener(String name, String id) {
								DataManager.getInstance(MainActivity.this)
										.saveContact(name, id);
								menuFragment.refreshContacts();
								addContactDialogFragment.dismiss();
							}

							@Override
							public void onCancelListener() {
								// TODO Auto-generated method stub

							}
						});
				addContactDialogFragment.show(fm, "addContactDialogFragment");
				// captureScreen();
			}

			@Override
			public void onEditContact(final String contact) {
				FragmentManager fm = getSupportFragmentManager();
				Bundle bundle = new Bundle();
				bundle.putString(EditContactDialogFragment.CONTACT_NAME,
						contact);
				final EditContactDialogFragment dialog = new EditContactDialogFragment();
				dialog.setArguments(bundle);
				dialog.setOnAddContactDialogListener(new EditContactDialogListener() {

					@Override
					public void onOKClickListener(String name, String id) {
						if (!contact.equals(name)) {
							DataManager.getInstance(MainActivity.this)
									.removeContact(contact);
						}
						DataManager.getInstance(MainActivity.this).saveContact(
								name, id);
						menuFragment.refreshContacts();
						dialog.dismiss();
					}

					@Override
					public void onDelete(String name) {
						DataManager.getInstance(MainActivity.this)
								.removeContact(name);
						menuFragment.refreshContacts();
						dialog.dismiss();
					}

					@Override
					public void onCancelListener() {

					}
				});
				dialog.show(fm, "EditContactDialogFragment");
			}

			@Override
			public void onRateApp() {
				RateAppManager.getInstance(MainActivity.this).rateApp();
			}

			@Override
			public void onHideApp() {
				// PackageManager p = getPackageManager();
				// p.setComponentEnabledSetting(getComponentName(),
				// PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
				// PackageManager.DONT_KILL_APP);
				showConfirmHideApp();
			}
		});
		t.replace(R.id.menu_frame, menuFragment);
		t.commit();
		menu = getSlidingMenu();
		menu.setMode(SlidingMenu.LEFT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		menu.setBehindWidthRes(R.dimen.sliding_menu_width);
		// menu.setBehindOffset(100);

	}

	protected void showConfirmHideApp() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("This app will be hide from launcher. Press *123456# to show this app again. Do you want hide app?");

		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				PackageManager p = getPackageManager();
				ComponentName componentName = new ComponentName(
						MainActivity.this, MainActivity.class);
				p.setComponentEnabledSetting(componentName,
						PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
						PackageManager.DONT_KILL_APP);

				finish();
			}
		});

		builder.setNeutralButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		builder.create().show();

	}

	protected void sendRequest(String contactName) {
		hideNotice();
		if (!isDone) {
			return;
		}
		isDone = false;
		showProgessbar("Connecting to " + currentContact + "...");
		new CountDownTimer(TIME_OUT, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {
				if (isDone) {
					this.cancel();
				}
			}

			@Override
			public void onFinish() {
				if (!isDone) {
					showNotice("Can't connect to " + currentContact
							+ ". Please try again!");
				}
				hideProgessbar();
				isDone = true;
			}
		}.start();
		KiraMessage kiraMessage = new KiraMessage();
		kiraMessage.setMessageType(MessageType.SEND_REQUEST);
		QuickBloxManager.getInstance(MainActivity.this).sendMessage(
				Integer.parseInt(contactName), kiraMessage.toJson());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		KiraGameLog.d("onDestroy");
		unregisterReceiver(networkReceiver);
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				changeUIReceiver);
		QuickBloxManager.getInstance(this).onDestroy();
		startAppService();
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		if (spinner != null) {
			if (isShowingProgessbar) {
				return;
			}
		}
		super.onBackPressed();
	}

	private void startAppService() {
		// Intent service = new Intent(MainActivity.this, AppService.class);
		// startService(service);
		Intent intent = new Intent(MainActivity.this,
				ServiceAppBroadcastReceiver.class);
		sendBroadcast(intent);
	}

	public void showGetImageError(String reason) {
		if (isDone) {
			return;
		}
		isDone = true;
		KiraGameLog.d("show image fail " + reason);
		showNotice(reason);
		hideProgessbar();
	}

	public void showImageContent(String content) {
		if (isDone) {
			return;
		}
		isDone = true;
		KiraGameLog.d("show image " + content);
		hideProgessbar();

		AQuery aq = new AQuery(this);
		aq.id(tvImage).progress(pbLoading)
				.image(content, false, false, 0, 0, new BitmapAjaxCallback() {
					@Override
					public void callback(String url, ImageView iv, Bitmap bm,
							AjaxStatus status) {
						if (bm != null) {
							image = bm;
							tvImage.setImageBitmap(bm);
							pbLoading.setVisibility(View.GONE);
							ibDownload.setVisibility(View.VISIBLE);
							addRateAppDialog();
						}
					}
				});
		// Picasso.with(this).load(content).into(tvImage);
	}

	private BroadcastReceiver changeUIReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String actionUIMAin = intent
					.getStringExtra(QuickBloxManager.ACTION_UI_MAIN);
			String message = intent
					.getStringExtra(QuickBloxManager.MESSAGE_INFO);
			KiraGameLog.d("get broadcast receive with action " + actionUIMAin
					+ " and message " + message);
			switch (actionUIMAin) {
			case QuickBloxManager.ACTION_SHOW_PROGESSBAR:
				showProgessbar(message);
				break;
			case QuickBloxManager.ACTION_HIDE_PROGESSBAR:
				hideProgessbar();
				break;
			case QuickBloxManager.ACTION_SHOW_NOTICE:
				showNotice(message);
				break;

			case QuickBloxManager.ACTION_SHOW_ERROR:
				showGetImageError(message);
				break;
			case QuickBloxManager.ACTION_SHOW_IMAGE:
				showImageContent(message);
				break;
			default:
				break;
			}
		}
	};

	private class SaveImageTask extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			showProgessbar("Save image...!");
		}

		@Override
		protected String doInBackground(Void... params) {

			String root = Environment.getExternalStorageDirectory().toString();
			File newDir = new File(root + "/" + FOLDER_NAME);
			newDir.mkdir();
			String photoName = Long.toString(new Date().getTime()) + ".png";
			File file = new File(newDir, photoName);
			if (file.exists()) {
				file.delete();
			}
			FileOutputStream out;
			try {
				out = new FileOutputStream(file);
				image.compress(Bitmap.CompressFormat.PNG, 100, out);
				out.flush();
				out.close();
				return file.getAbsolutePath();
			} catch (FileNotFoundException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgessbar();
			if (result != null) {
				Toast.makeText(MainActivity.this, "Save image at " + result,
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(MainActivity.this, "Can not save this image!",
						Toast.LENGTH_LONG).show();
			}

		}

	}

}
